//
//  CJHomeTableViewController.swift
//  SinaWeibo
//
//  Created by 程建 on 16/9/22.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD
import YYModel

private let originalCellId = "CJStatusCellID"
private let retweetedID = "CJRetweetedID"

class CJHomeTableViewController: CJBaseTableViewController {


    //懒加载数据源数组
   // lazy var statuses:[CJStatus] = [CJStatus]()
    //视图控制器引用viewModel
    lazy var homeViewModel:CJHomeViewModels = CJHomeViewModels()
    
    //实例化小菊花 懒加载
    lazy var indicatorView:UIActivityIndicatorView = {
        
        let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        
        //测试转动时,应该在加载更多数据时开始转动
    
        return indicator
    }()
    
    //懒加载label
    private lazy var tipLabel:UILabel = {
        
        let tipLabel = UILabel(title: "", textColor: UIColor.white, fontSize: 14)
        
        //设置背景颜色
        tipLabel.backgroundColor = UIColor.orange
        
        //设置居中
        tipLabel.textAlignment = .center
        
        tipLabel.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 35)
        
        tipLabel.isHidden = true
        
        return tipLabel
        
    }()
    
    
    //下拉刷新控件
    let cjRefreshControl = CJRefreshControl()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !userLogin {
        
            visitorView.updateInfo(title: "关注一些人,快回到这里看看有什么惊喜", imageName: nil)
            
            return
        }
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: #selector(push))
        
        //在请求数据之前设置tableView
        setupTableView()
        
        loadData()
        
       
    }
    
    
    func setupTableView() {
        
        //注册原创微博cell
        tableView.register(UINib(nibName: "CJStatusCell", bundle: nil), forCellReuseIdentifier: originalCellId)
        
        //注册转发微博cell
        tableView.register(UINib(nibName:"CJRetweeted", bundle: nil), forCellReuseIdentifier: retweetedID)
        
        
        //设置行高
       // tableView.rowHeight = 300

        //设置分割线
        tableView.separatorStyle = .none
        
        //设置小菊花在尾部
        tableView.tableFooterView = indicatorView
        
        //添加系统的刷新控件
   /*     refreshControl = UIRefreshControl()
        
        //添加监听事件
        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
        tipLabel.frame.origin.y = navBarHeight - 35
        self.navigationController?.view.addSubview(tipLabel)
 */
        
        
        cjRefreshControl.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
        self.view.addSubview(cjRefreshControl)
        
        //将tipLabel放在导航条下面
        self.navigationController?.view.insertSubview(tipLabel, belowSubview: self.navigationController!.navigationBar)
    
    }
    
    internal func loadData() {
        
        homeViewModel.loadData(isPullup: indicatorView.isAnimating) { (success,count) in
            if !success {
                
                SVProgressHUD.showError(withStatus: errorTip)
                
                return
            }
            //停止动画
            //self.refreshControl?.endRefreshing()
            
           // self.cjRefreshControl.refreshStatue = .Normal
            
            self.cjRefreshControl.stopAnimation()
            
            
            //执行label的动画效果
            
            if !self.indicatorView.isAnimating {
                 self.startTipLabelAnimation(count:count)
            }
            
            //让小菊花停止转动
            self.indicatorView.stopAnimating()
            
            //成功刷新数据
            self.tableView.reloadData()
            
        }
        
    }
    
    //动画效果的方法
    func startTipLabelAnimation(count:Int){
        
        if tipLabel.isHidden == false {
            
            return
        
        }
        
        //设置文字
        tipLabel.text = count == 0 ? "没有新微博数据":"有\(count)条新微博数据"
        //执行动画效果
        //动画执行前
        tipLabel.isHidden = false
        UIView.animate(withDuration: 1, animations: { 
            self.tipLabel.frame.origin.y = navBarHeight
            }) { (_) in
                UIView.animate(withDuration: 1, delay: 1, options: [], animations: { 
                    self.tipLabel.frame.origin.y = navBarHeight - 35
                    }, completion: { (_) in
                        self.tipLabel.isHidden = true
                })
        }
    }
    
    
    
    //按钮的点击事件
    @objc private func push() {
        
        let temp = CJTempViewController()
        //push到子页面
        self.navigationController?.pushViewController(temp, animated: true)
    }
        
}



//实现数据源方法
//这里不需要遵守协议,重复遵守会报错
extension CJHomeTableViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        //懒加载的好处不需要考虑可选类型的使用
        return homeViewModel.viewModelArray.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let viewModel = homeViewModel.viewModelArray[indexPath.row]
        
        //调用方法获取cellID
        let cellID = getCellIdWithViewmodel(viewModel: viewModel)
        
        //获取两种的重用标识符不一样大的同种类型的cell
        let cell = tableView.dequeueReusableCell(withIdentifier: cellID, for: indexPath) as! CJStatusCell
        
        
        cell.viewModel = viewModel
        
       // print(viewModel.status?.pic_urls?.last?.thumbnail_pic)
              
        return cell
    }
    
    
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let viewModels = homeViewModel.viewModelArray[indexPath.row]
        //根据数据获取对应的cell
        let cellID = getCellIdWithViewmodel(viewModel: viewModels)
        //计算高度不能够通过从缓冲池获取cell的方式
        //自己从nib中读取cell对象的方式 和可重用的cell没有任何关系
        let cell = cellWithId(cellID: cellID)
        
        let rowHight = cell.rowHeight(viewmodels: viewModels)
        
        return rowHight
    }
    
  
    
    //根据数据获取对应的cell对象
    private func cellWithId(cellID:String) -> CJStatusCell {
        let nibName = cellID == originalCellId ? "CJStatusCell":"CJRetweeted"
        
        return UINib(nibName: nibName, bundle: nil).instantiate(withOwner: nil, options: nil).last as! CJStatusCell
        
    }
    
    //根据viewModel判断使用那种cellID
    private func getCellIdWithViewmodel(viewModel:CJStatusViewModel)-> String {
        
        if viewModel.status?.retweeted_status == nil {
            //原创微博
            return originalCellId
        }
        //转发微博
        return retweetedID
    }
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        if indexPath.row == homeViewModel.viewModelArray.count - 2 && indicatorView.isAnimating == false {
            
            indicatorView.startAnimating()
            
            loadData()
            
            print("开始执行加载数据")
            print("☺️😝😝😝😝😝😝😝😝😝😝😝😝😝")
            
        }
        
    }

}
